package xzl.edu.cn.set.demo;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class FileDemo {
	Logger logger = LogManager.getLogger(FileDemo.class);

	/**
	 * 字符流写文件
	 * 
	 * @param filename 文件名
	 * @param text     文件内容
	 */
	public void writeFile(String filename, String text) {
		File file = new File(filename);
		try {
			FileWriter fileWriter = new FileWriter(file);
			fileWriter.write(text);
			fileWriter.close();
			logger.info("写入成功！");
		} catch (FileNotFoundException e) {
			logger.info("该文件不存在！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("写入失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 字符流读文件
	 * 
	 * @param filename
	 */
	public void readFile(String filename) {
		File file = new File(filename);
		char ch[] = new char[(int) file.length()];
		try {
			FileReader fileReader = new FileReader(file);
			fileReader.read(ch);
			logger.info(new String(ch));
			fileReader.close();
		} catch (FileNotFoundException e) {
			logger.info("该文件不存在！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("读取失败！");
			e.printStackTrace();
		}
	}

	/**
	 * 字节流写文件
	 * 
	 * @param filename 文件名
	 * @param text     文件内容
	 */
	public void writeOutstream(String filename, String text) {
		File file = new File(filename);
		try {
			OutputStream out = new FileOutputStream(file);
			byte b[] = new byte[(text.getBytes()).length];
			out.write(b);
			out.close();
			logger.info("写入成功！");
		} catch (FileNotFoundException e) {
			logger.info("该文件不存在！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("写入失败！");
			e.printStackTrace();

		}
	}

	/**
	 * 字节流读文件
	 * 
	 * @param filename
	 */
	public void readIostream(String filename) {
		File file = new File(filename);
		byte b[] = new byte[(int) file.length()];
		try {
			InputStream in = new FileInputStream(filename);
			in.read(b);
			in.close();
			logger.info(new String(b));

		} catch (FileNotFoundException e) {
			logger.info("该文件不存在！");
			e.printStackTrace();
		} catch (IOException e) {
			logger.info("读取失败！");
			e.printStackTrace();
		}

	}

}
